use std::sync::Arc;

use crate::emitter::EventHandler;
use crate::{config::Config, emitter::Emitter, rpc::RPCService};
use tokio::sync::Mutex;
use tokio::sync::MutexGuard;

#[derive(Debug)]
pub struct State {
    pub config: Config,
    pub rpc: RPCService,
    pub emitter: Mutex<Emitter>,
}

pub fn create_state(cfg: Config) -> Arc<State> {
    let mut rpc = RPCService::new();
    rpc.key = cfg.rpc_secret.clone();
    rpc.port = cfg.app_port;

    let state_arc = Arc::new(
        (State {
            config: cfg,
            rpc,
            emitter: Mutex::new(Emitter::new()),
        }),
    );

    tokio::task::spawn_blocking(async {
        state_arc.emitter.lock().await.add_handler();
    });

    state_arc
}
